﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using ApplicationLibrary;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.SqlConnector;
using Plumber.Accounting.Forms;
using Plumber.Accounting.ModuleData;
using Plumber.Accounting.Reports.DataSet;
using Plumber.Masters.ModuleData;
using ApplicationLibrary.CounterManager;
using Plumber.Accounting.Library;

namespace Plumber.Accounting.Reports
{
    public partial class ClientsSuppliers : ApplicationLibrary.DBManager.ReportForm
    {
        private string Title = string.Empty;
        private Dictionary<string, totals> list = new Dictionary<string, totals>();
        private DSClientSupplier dsClientSupplier = null;
        private DRMasters drMasters = null;
        private DRMasterTypeByType drMastersByType = null;
        private string condominium;

        public ClientsSuppliers()
            : base(Properties.Resources.FN_MonthlySummary)
        {
            InitializeComponent();
        }

        protected override void OnBatchExecute(string reportName)
        {
            //Title = string.Format("{0}_{1}_{2}", Properties.Resources.FN_MonthlySummary, cbbMonth.Text, cbbYear.Text);
            if (!LoadData())
            {
                MessageBox.Show(Properties.Resources.Msg_NoDataPeriod, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SetParameterValue("Title", string.Format(Properties.Resources.Msg_CustomerSupplier, cbbRegister.Text, cbbYear.Text));
            ShowReport(new RPTClientSupplier(), dsClientSupplier);

        }

        protected override void OnDisableControlsForRun()
        {
        }

        protected override void OnAttachData()
        {
            dsClientSupplier = new DSClientSupplier();
            drMasters = new DRMasters(false);
            drMastersByType = new DRMasterTypeByType();

            drMastersByType.Find(MasterTypes.E_Condominium);
            condominium = drMastersByType.GetValue<string>(PL_MasterType.Code);

            cbbYear.Text = GlobalInfo.CurrentDate.Year.ToString();

            for (int t = 2011; t <= GlobalInfo.CurrentDate.Year; t++)
                cbbYear.Items.Add(t);
            cbbYear.Text = (GlobalInfo.CurrentDate.Year-1).ToString();
        }

        protected override void OnBindData()
        {
        }


        private bool LoadData()
        {
            QueryBuilder qb = new QueryBuilder(true);
            qb.Clear();
            qb.AddSelect(PL_JournalEntry.DocumentNo);
            qb.AddSelect(PL_JournalEntry.DocumentDate);
            qb.AddSelect(PL_JournalEntry.JournalNo);
            qb.AddSelect(PL_JournalEntry.PostingDate);
            qb.AddSelect(PL_JournalEntry.Type);
            qb.AddSelect(PL_JournalEntry.Code);
            qb.AddSelect(PL_JournalEntry.Description);

            qb.AddSelectAll(PL_JournalEntryTaxDetail.Name);
            qb.AddFrom(PL_JournalEntryTaxDetail.Name);
            qb.AddJoin(QueryBuilder.JoinType.INNER, PL_JournalEntry.JournalNo, PL_JournalEntryTaxDetail.JournalNo);
            SqlABParameter pFrom = new SqlABParameter("@p1", PL_JournalEntry.PostingDate);
            SqlABParameter pTo = new SqlABParameter("@p2", PL_JournalEntry.PostingDate);
            qb.AddBetween(PL_JournalEntry.PostingDate, pFrom, pTo);
            if (cbbRegister.SelectedIndex == 0)
                qb.AddCompare<TaxRegisterType>(PL_JournalEntry.TaxRegister, TaxRegisterType.E_TaxSale);
            else
                qb.AddCompare<TaxRegisterType>(PL_JournalEntry.TaxRegister, TaxRegisterType.E_TaxPurchase);

            pFrom.Value = new DateTime(cbbYear.Text.Int(), 1, 1);
            pTo.Value = new DateTime(cbbYear.Text.Int(), 12, 31);

            list.Clear();
            using (SqlABCommand scc = new SqlABCommand(base.providerType, GlobalInfo.SqlConnection))
            {
                scc.CommandText = qb.Query;
                scc.Parameters.Add(pFrom);
                scc.Parameters.Add(pTo);
                SqlABDataReader dr = scc.ExecuteReader();
                while (dr.Read())
                    ElaborateRow(dr);
                dr.Close();
            }


            dsClientSupplier.Clear();

            foreach (KeyValuePair<string, totals> lst in list)
            {
                DSClientSupplier.ClientsSuppliersRow csr = dsClientSupplier.ClientsSuppliers.NewClientsSuppliersRow();
                drMasters.Find(lst.Value.Type, lst.Value.Code);
                csr[PL_Masters.Description.Name] = lst.Value.Type == condominium
                                                        ? drMasters.GetValue<string>(PL_Masters.Address)
                                                        : drMasters.GetValue<string>(PL_Masters.Description);
                csr[PL_Masters.Description.Name] = csr[PL_Masters.Description.Name].ToString().Replace("\r\n", " ").TrimStart().TrimEnd();
                csr[PL_Masters.TaxNo.Name] = drMasters.GetValue<string>(PL_Masters.TaxNo); ;
                csr[PL_Masters.FiscalCode.Name] = drMasters.GetValue<string>(PL_Masters.FiscalCode); ;
                csr["DocumentNo"] = lst.Value.Number;
                csr["Amount"] = lst.Value.Amount;
                csr["Tax"] = lst.Value.Tax;
                dsClientSupplier.ClientsSuppliers.Rows.Add(csr);
            }
            return dsClientSupplier.ClientsSuppliers.Rows.Count > 0;
        }

        private void ElaborateRow(SqlABDataReader dr)
        {
            string key = string.Format("{0}-{1}", dr.GetValue<string>(PL_JournalEntry.Type), dr.GetValue<string>(PL_JournalEntry.Code));
            if (!list.ContainsKey(key))
                list.Add(key, new totals()
                    {
                        Type = dr.GetValue<string>(PL_JournalEntry.Type),
                        Code = dr.GetValue<string>(PL_JournalEntry.Code)
                    }
                );

            //if (dr.GetValue<double>(PL_JournalEntryTaxDetail.Tax) != 0)
            //{
                list[key].Amount += dr.GetValue<double>(PL_JournalEntryTaxDetail.Amount);
                list[key].Tax += dr.GetValue<double>(PL_JournalEntryTaxDetail.Tax);

                if (dr.GetValue<int>(PL_JournalEntryTaxDetail.Line) == 1)
                    list[key].Number++;
            //}
        }

        private void AddRow(SqlABDataReader dr)
        {
            //double amount, tax;
            //string taxcode;
            //DSTaxRegister.JournalEntryTaxDetailRow jer = dsTaxRegister.JournalEntryTaxDetail.NewJournalEntryTaxDetailRow();
            //jer[PL_JournalEntry.DocumentNo.Name] = dr.GetValue<string>(PL_JournalEntry.DocumentNo);
            //jer[PL_JournalEntry.DocumentDate.Name] = dr.GetValue<DateTime>(PL_JournalEntry.DocumentDate);
            //jer[PL_JournalEntry.JournalNo.Name] = dr.GetValue<string>(PL_JournalEntry.JournalNo);
            //jer[PL_JournalEntry.PostingDate.Name] = dr.GetValue<DateTime>(PL_JournalEntry.PostingDate);
            //drMasterType.Find(dr.GetValue<string>(PL_JournalEntry.Type));
            //jer[PL_JournalEntry.Type.Name] = drMasterType.GetValue<string>(PL_MasterType.Description);
            //jer[PL_JournalEntry.Code.Name] = dr.GetValue<string>(PL_JournalEntry.Code);
            //jer[PL_JournalEntry.Description.Name] = dr.GetValue<string>(PL_JournalEntry.Description);

            //jer[PL_JournalEntryTaxDetail.Amount.Name] = amount = dr.GetValue<double>(PL_JournalEntryTaxDetail.Amount);
            //jer[PL_JournalEntryTaxDetail.Tax.Name] = tax = dr.GetValue<double>(PL_JournalEntryTaxDetail.Tax);
            //jer[PL_JournalEntryTaxDetail.Total.Name] = amount + tax;
            //taxcode = dr.GetValue<string>(PL_JournalEntryTaxDetail.TaxCode);

            //drTaxCode.Find(taxcode);
            //jer[PL_JournalEntryTaxDetail.TaxCode.Name] = drTaxCode.GetValue<string>(PL_TaxCode.Description);

            //dsTaxRegister.JournalEntryTaxDetail.Rows.Add(jer);

            //if (!taxTotals.ContainsKey(taxcode))
            //    taxTotals.Add(taxcode, new totals());

            //taxTotals[taxcode].Amount += amount;
            //taxTotals[taxcode].Tax += tax;
        }

        protected override EmailArgs SendEmail()
        {
            EmailArgs ea = new EmailArgs();
            ea.Subject = Title;
            ea.Attachment = ExportToPdf(Title);
            return ea;
        }

        private class totals
        {
            public string Type { get; set; }
            public string Code { get; set; }
            public double Amount { get; set; }
            public double Tax { get; set; }
            public int Number { get; set; }
        }
    }
}